﻿using AutoMapper;
using Serilog;
using SqlSugar;
using System.Linq.Expressions;
using WCS_Entity.Dto.UpperSysDto;
using WCS_Entity.Entity.UpperSys;
using WCS_Repository.Interface;
using WCS_Service.Interface;

namespace WCS_Service.Services
{
    /// <summary>
    /// 上位系统配置服务
    /// </summary>
    public class UpperSysService : BaseService<UpperSysServiceEntity>, IUpperSysService
    {

        private readonly IUpperSysServiceRepository _upperSysServiceRepository;
        private readonly IMapper _mapper;

        public UpperSysService(IUpperSysServiceRepository upperSysServiceRepository,
                          IMapper mapper)
        {
            _upperSysServiceRepository = upperSysServiceRepository;
            _mapper = mapper;
        }

        public async Task<UpperSysDto> CreateUppserSysAsync(CreatUpperSysDto dto)
        {
            UpperSysDto result = new UpperSysDto();
            var flag = await _upperSysServiceRepository.ExistsAsync(r => r.upperSys == dto.upperSys);
            if (flag)
            {
                Log.Error($"创建上位服务{dto.upperSys}已经存在");
                return null;
            }
            var entity = _mapper.Map<UpperSysServiceEntity>(dto);

            entity.createTime = DateTime.Now;

            await _upperSysServiceRepository.InsertAsync(entity);

            result = _mapper.Map<UpperSysDto>(entity);
            return result;
        }

        public async Task<bool> DeleteUppserSys(int id)
        {
            return await _upperSysServiceRepository.DeleteByIdAsync(id);
        }

        public async Task<List<UpperSysDto>> QueryAllUppserSysAsync()
        {
            List<UpperSysDto> result = new List<UpperSysDto>();
            Expression<Func<UpperSysServiceEntity, object>> orderEx = p => p.createTime;
            var entityInfos = await _upperSysServiceRepository.QueryPageAsync(null, orderEx, OrderByType.Desc, 1, 10);
            if (entityInfos is null || !entityInfos.Any())
            {
                Log.Error("查询所有上位服务失败");
                return null;
            }
            List<Task<UpperSysDto>> entityList = new List<Task<UpperSysDto>>();
            foreach (var entityInfo in entityInfos)
            {
                entityList.Add(GetDtoInfoAsync(entityInfo));
            }
            await Task.WhenAll(entityList);
            result = entityList.Select(e => e.Result).ToList();
            return result;
        }

        public async Task<UpperSysDto> QueryUppserSysAsync(int id)
        {
            UpperSysDto result = new UpperSysDto();

            var entityInfo = await _upperSysServiceRepository.QueryByIdAsync(id);
            if (entityInfo is null)
            {
                Log.Error($"查询指定上位服务{id}失败");
                return null;
            }
            result = _mapper.Map<UpperSysDto>(entityInfo);
            return result;
        }

        public async Task<UpperSysDto> UpdateUppserSysAsync(UpdateUpperSysDto dto)
        {
            UpperSysDto result = new UpperSysDto();
            var entityInfo = await _upperSysServiceRepository.QueryByIdAsync(dto.id);
            if (entityInfo is null)
            {
                Log.Error($"编辑上位服务{dto.id}失败");
                return null;
            }
            if (entityInfo.ip != dto.ip)
            {
                entityInfo.ip = dto.ip;
            }
            if (entityInfo.port != dto.port)
            {
                entityInfo.port = dto.port;
            }
            if (entityInfo.status != dto.status)
            {
                entityInfo.status = dto.status;
            }
            if (entityInfo.isHttps != dto.isHttps)
            {
                entityInfo.isHttps = dto.isHttps;
            }
            if (entityInfo.upperSys != dto.upperSys)
            {
                entityInfo.upperSys = dto.upperSys;
            }
            if (entityInfo.serviceToken != dto.serviceToken)
            {
                entityInfo.serviceToken = dto.serviceToken;
            }

            entityInfo.updataTime = DateTime.Now;

            await _upperSysServiceRepository.UpdateAsync(entityInfo);
            result = _mapper.Map<UpperSysDto>(entityInfo);
            return result;
        }
        /// <summary>
        /// 查找有效的上位服务
        /// </summary>
        /// <returns></returns>
        public async Task<List<UpperSysDto>> QueryEffectiveUpperSysAsync()
        {
            List<UpperSysDto> result = new List<UpperSysDto>();
            Expression<Func<UpperSysServiceEntity, bool>> orderEx = p => p.status == 1;
            var entityInfos = await _upperSysServiceRepository.QueryListByClauseAsync(orderEx);
            if (entityInfos is null || !entityInfos.Any())
            {
                Log.Error("查询所有有效上位服务失败");
                return null;
            }
            List<Task<UpperSysDto>> entityList = new List<Task<UpperSysDto>>();
            foreach (var entityInfo in entityInfos)
            {
                entityList.Add(GetDtoInfoAsync(entityInfo));
            }
            await Task.WhenAll(entityList);
            result = entityList.Select(e => e.Result).ToList();
            return result;
        }
        #region private
        private async Task<UpperSysDto> GetDtoInfoAsync(UpperSysServiceEntity entity)
        {
            return await Task.Run(() => _mapper.Map<UpperSysDto>(entity));
        }
        #endregion
    }
}
